<template>
  <el-dialog
    title="销售单信息"
    :visible.sync="centerDialogVisible"
    width="80%"
    center
    @open="init"
    append-to-body
  >
    <div class="app_main">
      <div class="table_box">
        <el-form ref="cuForm" v-loading="formLoading" :model="cuForm" :rules="rules" :disabled="true">
          <table class="mailTable">
            <tr>
              <td colspan="4" style="border: none">
                <div class="flex flex-no-wrap justify-between">
                  <div style="font-weight: bold">
                    合同编号:
                    <span :class="cuForm.contract_num?'text-red':''"
                    >{{ cuForm.contract_num ? cuForm.contract_num : '选择完合同自动填充' }}</span>
                  </div>
                  <div style="text-align: right;font-weight: bold">
                    <span style="margin-right: 20px">填表日期:</span>
                    <span>{{ cuForm.fill_date|formatDate }}</span>
                  </div>
                </div>
              </td>
            </tr>
            <tr class="firstTr">
              <td class="firstTd tip_td">
                <span class="tip">*</span>项目名称
              </td>
              <td class="column content_td">
                <el-form-item prop="customer_id">
                  <el-select v-model="cuForm.customer_id" :disabled="is_update" style="width: 100%" filterable
                             @change="customerChange"
                  >
                    <el-option v-for="item in customerArr" :key="item.id" :value="item.id" :label="item.name"/>
                  </el-select>
                </el-form-item>
              </td>
              <td class="tip_td">
                <span class="tip">*</span>客户合同名称
              </td>
              <td class="column content_td">
                <el-form-item prop="contract_id">
                  <el-select v-model="cuForm.contract" :disabled="is_update" style="width: 100%" filterable
                             value-key="id"
                             @change="contractChange"
                  >
                    <el-option v-for="item in contractArr" :key="item.id" :value="item"
                               :label="item.part_a+'——'+item.contract_num"
                    />
                  </el-select>
                </el-form-item>
                <div v-if="!is_created">
                  {{ cuForm.plan_name }}
                </div>
              </td>
            </tr>
            <tr>
              <td class="firstTd tip_td">
                <span class="tip">*</span>公司名称
              </td>
              <td class="column" colspan="3">
                <el-form-item prop="dept_id">
                  <el-select v-model="cuForm.dept_id" style="width: 100%">
                    <el-option v-for="item in companyArr" :key="item.id" :value="item.id" :label="item.head"/>
                  </el-select>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td class="firstTd tip_td">
                <span class="tip">*</span>锁位方案
              </td>
              <td class="column content_td">
                <el-form-item prop="intention_scheme_id">
                  <el-select v-model="cuForm.intention_scheme" :disabled="is_update" style="width: 100%" filterable
                             value-key="id"
                             @change="(val)=>{planChange(val,true)}"
                  >
                    <el-option v-for="item in planArr" :key="item.id" :value="item"
                               :label="item.plan_name"
                    />
                  </el-select>
                </el-form-item>
                <div v-if="!is_created">
                  {{ cuForm.plan_name }}
                </div>
              </td>
              <td class="tip_td">
                合同金额
              </td>
              <td class="column content_td">
                {{
                  discounted_price ? discounted_price + '元' : discounted_price
                }}
              </td>
            </tr>
            <tr>
              <td rowspan="4" class="firstTd tip_td">
                <span class="tip">*</span>实际执行时间
              </td>
              <td rowspan="4" class="column content_td">
                {{
                  cuForm.actual_execute_time_start ? cuForm.actual_execute_time_start + '~' + cuForm.actual_execute_time_end : '选择锁位后自动显示'
                }}
                <div>总天数：{{ getDaysBetween(cuForm.actual_execute_time_start, cuForm.actual_execute_time_end) }}</div>
              </td>
              <td class="tip_td">
                本次广告发布金额
              </td>
              <td class="column content_td">
                <el-form-item prop="release_amount">
                  <el-input v-model="cuForm.release_amount" type="number" step="0.01" placeholder="请输入广告发布金额">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td class="tip_td">
                本次换画金额
              </td>
              <td class="column content_td">
                <el-form-item prop="replace_amount">
                  <el-input v-model="cuForm.replace_amount" type="number" step="0.01" placeholder="请输入换画金额">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td class="tip_td">
                刊例总价
              </td>
              <td class="column content_td" style="padding: 0">
                <div v-show="cuForm.intention_scheme_id != null" style="padding: 10px 10px">
                  <el-table border size="mini" :data="media_type_count_amount_arr" style="margin: 0 auto;">
                    <el-table-column align="center" min-width="15" label="媒体类型" prop="name"/>
                    <el-table-column align="center" min-width="10" label="数量" prop="spec_count"/>
                    <el-table-column align="center" min-width="10" label="价格" prop="amount"/>
                  </el-table>
                </div>
                <!--              <table class="mailTable">-->
                <!--                <tr class="firstTr">-->
                <!--                  <td class="firstTd column">-->
                <!--                    媒体类型-->
                <!--                  </td>-->
                <!--                  <td class="column">-->
                <!--                    数量-->
                <!--                  </td>-->
                <!--                  <td class="column">-->
                <!--                    价格-->
                <!--                  </td>-->
                <!--                </tr>-->
                <!--                <tr v-for="(item,index) in media_type_count_amount_arr" :key="index">-->
                <!--                  <td class="firstTd column">-->
                <!--                    {{ item.name }}-->
                <!--                  </td>-->
                <!--                  <td class="column">-->
                <!--                    {{ item.spec_count }}-->
                <!--                  </td>-->
                <!--                  <td class="column">-->
                <!--                    {{ item.amount }}-->
                <!--                  </td>-->
                <!--                </tr>-->
                <!--              </table>-->
              </td>
            </tr>
            <tr>
              <td class="tip_td">
                <span class="tip">*</span>本次执行金额
              </td>
              <td class="column content_td">
                <el-form-item prop="execute_amount">
                  {{ execute_amount ? execute_amount + '元' : '' }}
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td class="firstTd tip_td">
                <span class="tip">*</span>媒体形式（必须标注每个类别对应的数量和金额）
              </td>
              <td class="column" colspan="3">
                <div v-show="cuForm.intention_scheme_id != null" style="max-width: 100%;overflow: auto">
                  <el-table :data="cuForm.billSaleMediaAmountList" border size="mini"
                            style="margin: 10px auto;width: 95%"
                  >
                    <el-table-column align="center" min-width="20" label="媒体类型" prop="name"/>
                    <el-table-column align="center" min-width="10" label="数量" prop="media_count"/>
                    <el-table-column align="center" min-width="10" label="单价">
                      <template slot-scope="scope">
                        <!--                      <div>-->
                        <!--                        <div v-if="scope.row.has_price_day">-->
                        <!--                          日价格：{{ scope.row.day_price ? (scope.row.day_price + '元') : '请先填写总价' }}-->
                        <!--                        </div>-->
                        <!--                        <div v-if="scope.row.has_price_week">-->
                        <!--                          周价格：{{ scope.row.week_price ? (scope.row.week_price + '元') : '请先填写总价' }}-->
                        <!--                        </div>-->
                        <!--                        <div v-if="scope.row.has_price_month">-->
                        <!--                          月价格：{{ scope.row.month_price ? (scope.row.month_price + '元') : '请先填写总价' }}-->
                        <!--                        </div>-->
                        <!--                      </div>-->
                        <div>
                          <div v-if="scope.row.has_price_day">
                            日价格：{{
                              fillAmountChange(scope.row, 'day', scope.row.fill_amount) ? (fillAmountChange(scope.row, 'day', scope.row.fill_amount) + '元') : '请先填写总价'
                            }}
                          </div>
                          <div v-if="scope.row.has_price_week">
                            周价格：{{
                              fillAmountChange(scope.row, 'week', scope.row.fill_amount) ? (fillAmountChange(scope.row, 'week', scope.row.fill_amount) + '元') : '请先填写总价'
                            }}
                          </div>
                          <div v-if="scope.row.has_price_month">
                            月价格：{{
                              fillAmountChange(scope.row, 'month', scope.row.fill_amount) ? (fillAmountChange(scope.row, 'month', scope.row.fill_amount) + '元') : '请先填写总价'
                            }}
                          </div>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" min-width="10" label="总价">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.fill_amount"
                                  :prop="'billSaleMediaAmountList.'+scope.$index+'.fill_amount'" size="mini"
                                  type="number"
                                  step="0.01"
                                  placeholder="请输入总价" :rules="{required: true, message: '总价不能为空', trigger: 'blur'}"
                        >
                          <template slot="append">元</template>
                        </el-input>
                        <!--                      {{ setFillAmount(scope.row.price, scope.row.media_count, scope.$index) }}元-->
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </td>
            </tr>
            <template v-for="(item,i) in cuForm.billSaleProxyList">
              <tr>
                <td rowspan="2" class="firstTd tip_td">
                  代媒体形式{{ cuForm.billSaleProxyList.length === 1 ? '' : (i + 1) }}
                </td>
                <td rowspan="2" class="column content_td">
                  <table v-if="cuForm.contract_id != null" class="proxyTable">
                    <tr class="firstTr">
                      <td class="firstTd column" style="width:30%;font-weight: bold;font-size: 12px;color: #909399">
                        媒体类型
                      </td>
                      <td class="column" style="width:15%;font-weight: bold;font-size: 12px;color: #909399">
                        规格
                      </td>
                      <td class="column" style="width:10%;font-weight: bold;font-size: 12px;color: #909399">
                        数量
                      </td>
                      <td class="column" style="width:15%;font-weight: bold;font-size: 12px;color: #909399">
                        时长
                      </td>
                      <td class="column" style="width:15%;font-weight: bold;font-size: 12px;color: #909399">
                        金额
                      </td>
                      <td class="column" style="width:15%;font-weight: bold;font-size: 12px;color: #909399">
                        刊例总价
                      </td>
                    </tr>
                    <tr v-if="(item.proxyMediaDetailList||[]).length>0"
                        v-for="(media,index) in item.proxyMediaDetailList"
                        :key="index"
                    >
                      <td class="firstTd column">
                        <el-form-item
                          :prop="'billSaleProxyList.'+ i+'.proxyMediaDetailList.'+index + '.proxy_media_type'"
                          :rules="{required: true, message: '媒体类型不能为空', trigger: 'blur'}"
                        >
                          <el-input v-model="media.proxy_media_type" size="mini" style="width: 90%" clearable/>
                        </el-form-item>
                      </td>
                      <td class="column">
                        <el-form-item
                          :prop="'billSaleProxyList.'+ i+'.proxyMediaDetailList.'+index + '.media_type_spec'"
                          :rules="{required: true, message: '媒体规格不能为空', trigger: 'change'}"
                        >
                          <el-input v-model="media.media_type_spec" size="mini" style="width: 90%"/>
                        </el-form-item>
                      </td>
                      <td class="column">
                        <el-form-item :prop="'billSaleProxyList.'+ i+'.proxyMediaDetailList.'+index + '.quantity'"
                                      :rules="{required: true, message: '数量不能为空', trigger: 'blur'}"
                        >
                          <el-input v-model="media.quantity" size="mini" placeholder="请输入数量"/>
                        </el-form-item>
                      </td>
                      <td class="column">
                        <el-form-item :prop="'billSaleProxyList.'+ i+'.proxyMediaDetailList.'+index + '.duration'"
                                      :rules="{required: true, message: '时长不能为空', trigger: 'blur'}"
                        >
                          <el-input v-model="media.duration" size="mini" placeholder="请输入时长"/>
                        </el-form-item>
                      </td>
                      <td class="column">
                        <el-form-item :prop="'billSaleProxyList.'+ i+'.proxyMediaDetailList.'+index + '.amount'"
                                      :rules="{required: true, message: '金额不能为空', trigger: 'blur'}"
                        >
                          <el-input v-model="media.amount" size="mini" placeholder="请输入金额"/>
                        </el-form-item>
                      </td>
                      <td class="column">
                        <el-form-item :prop="'billSaleProxyList.'+ i+'.proxyMediaDetailList.'+index + '.fill_amount'"
                                      :rules="{required: true, message: '刊例总价不能为空', trigger: 'blur'}"
                        >
                          <el-input v-model="media.fill_amount" size="mini" placeholder="请输入刊例总价"/>
                        </el-form-item>
                      </td>
                    </tr>
                    <tr v-if="(item.proxyMediaDetailList||[]).length==0">
                      <td class="firstTd column" colspan="6" style="color: #909399">
                        {{ '暂无数据' }}
                      </td>
                    </tr>
                  </table>
                </td>
                <td class="tip_td">
                  代理公司名称
                </td>
                <td class="content_td" style="position: relative">
                  <el-form-item prop="proxy_company_name">
                    <el-input v-model="item.proxy_company_name" placeholder="请输入代理公司名称"/>
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td class="tip_td">
                  代理金额
                </td>
                <td class="content_td">
                  <el-form-item prop="proxy_amount">
                    <el-input v-model="item.proxy_amount" type="number" step="0.01" placeholder="请输入代理金额">
                      <template slot="append">元</template>
                    </el-input>
                  </el-form-item>
                </td>
              </tr>
            </template>
            <tr>
              <td class="tip_td firstTd" rowspan="2">
                <span class="tip">*</span>是否置换
              </td>
              <td class="column content_td" rowspan="2">
                <el-form-item prop="need_replace">
                  <el-radio-group v-model="cuForm.need_replace">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </td>
              <td class="tip_td">
                物品金额
              </td>
              <td class="column content_td">
                <el-form-item prop="item_amount">
                  <el-input v-model="cuForm.item_amount" type="number" step="0.01" placeholder="请输入物品金额">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td class="tip_td">
                现金金额
              </td>
              <td class="column content_td">
                <el-form-item prop="cash_amount">
                  <el-input v-model="cuForm.cash_amount" type="number" step="0.01" placeholder="请输入现金金额">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td class="firstTd tip_td">
                折扣
              </td>
              <td class="column content_td">
                <div v-show="cuForm.intention_scheme_id != null">
                  {{
                    cuForm.discount ? cuForm.discount + '%' : ''
                  }}
                </div>
              </td>
              <td class="tip_td">
                计提百分比
              </td>
              <td class="column content_td">
                <el-input v-model="cuForm.accrued_amount" style="width: 200px"
                          type="number"
                          step="0.01"
                          placeholder="请输入百分比"
                >
                  <template slot="append">%</template>
                </el-input>
                <span style="line-height: 40px;margin-left: 20px">
                    {{ commission }}
                </span>
              </td>
            </tr>
            <tr>
              <td class="firstTd tip_td">
                <span class="tip">*</span>收款时间
              </td>
              <td class="column content_td">
                <el-form-item prop="collection_time">
                  <el-date-picker
                    v-model="cuForm.collection_time"
                    type="date"
                    placeholder="请选择收款时间"
                    value-format="yyyy-MM-dd"
                    format="yyyy年MM月dd日"
                    style="width: 100%"
                  />
                </el-form-item>
              </td>
              <td class="tip_td">
                <span class="tip">*</span>是否开票
              </td>
              <td class="column content_td">
                <el-form-item prop="need_invoice">
                  <el-radio-group v-model="cuForm.need_invoice">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td class="tip_td firstTd">
                备注
              </td>
              <td class="column" colspan="3">
                <div style="padding: 10px 0">
                  <el-input v-model="cuForm.memo" type="textarea" placeholder="请输入备注" :rows="4"/>
                </div>
              </td>
            </tr>
          </table>
        </el-form>
      </div>
      <point-config v-if="cuForm.intention_scheme_id != null" v-loading="formLoading" :data="cuForm.tmpDataList"
                    :read-only="true"
      />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="centerDialogVisible = false">关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { get_company } from '@/api/system/department'
import { add, divide, multiply } from '@/utils/amount'
import { cloneDeep } from 'lodash/lang'
import { detail, media_type_count_amount } from '@/api/saleOrder'
import { detail as contractDetail, listByCustomerId } from '@/api/contract'
import { detail as planDetail, listByRelated } from '@/api/business/intention_scheme'
import { formatData } from '@/views/business/contract/util'
import { company_list_all, list_all } from '@/api/customer/customer'
import { formatDate, formatDateByFmt, getDaysBetween } from '@/utils/util'
import pointConfig from '@/components/PointPlanSetting/pointConfig'

export default {
  name: 'SaleOrderDialog',
  props: {
    saleOrderId: {
      type: Number,
      default: -1
    }
  },
  components: {
    pointConfig
  },
  filters: {
    formatDate(time) {
      if (time) {
        return formatDateByFmt(time, 'yyyy年MM月dd日')
      }
    }
  },
  data() {
    return {
      is_created: false,
      formLoading: false,
      cuForm: {
        // 客户id
        customer_id: null,
        // 合同id
        choose_id: null,
        // 点位选择id
        contract_choose_id: null,
        // 日期范围id
        contract_daterange_id: null,
        // 填表日期
        fill_date: formatDate(new Date()),
        // 合同ID
        contract_id: null,
        // 分公司id
        dept_id: null,
        actual_execute_time: [],
        // 实际执行开始时间
        actual_execute_time_start: null,
        // 实际执行结束时间
        actual_execute_time_end: null,
        // 本次发布金额
        release_amount: null,
        // 本次换画面金额
        replace_amount: null,
        // 本次执行金额
        execute_amount: null,
        // 代理公司名称
        proxy_company_name: null,
        // 代理金额
        proxy_amount: null,
        // 被代理公司名称
        proxied_company_name: null,
        // 被代理金额
        proxied_amount: null,
        // 是否置换：1：是，0：否
        need_replace: null,
        // 物品金额
        item_amount: null,
        // 现金金额
        cash_amount: null,
        // 计提额
        accrued_amount: null,
        // 收款时间
        collection_time: null,
        // 是否开发票：1：是，0：否
        need_invoice: null,
        // 备注
        memo: null,
        discount: null,
        // 媒体类型对应数量金额
        billSaleMediaAmountList: [],
        // 代理信息
        billSaleProxyList: [],
        tmpDataList: [],
        proxyInfo: [],
        proxyInfo2: [],
        contractAmount: null,
        dateRangeBeginDate: null,
        dateRangeEndDate: null,
        contractBeginDate: '',
        contractEndDate: '',
        contractName: '',
        contract: null,
        intention_scheme_id: null,
        intention_scheme: null,
        daterange_id: null,
        contract_num: null,
        update_accrued_amount: false
      },
      rules: {
        intention_scheme_id: [
          { required: true, message: '请选择锁位', trigger: 'change' }
        ],
        dept_id: [
          { required: true, message: '请选择所属公司', trigger: 'change' }
        ],
        need_replace: [
          { required: true, message: '请选择是否置换', trigger: 'change' }
        ],
        need_invoice: [
          { required: true, message: '请选择是否开票', trigger: 'change' }
        ],
        collection_time: [
          { required: true, message: '请选择收款时间', trigger: 'change' }
        ],
        customer_id: [
          { required: true, message: '请选择项目', trigger: 'change' }
        ],
        contract_id: [
          { required: true, message: '请选择合同', trigger: 'change' }
        ]
      },
      companyArr: [],
      contractArr: [],
      planArr: [],
      customerArr: [],
      discounted_price: null,
      errorData: {},
      dateRangeArr: [],
      customer_name: null,
      customer_id: null,
      media_name_arr: [],
      media_name_arr2: [],
      discountArr: [],
      media_type_count_amount_arr: [], // 刊例总价
      params: {},
      proxyMediaDetailList: [],
      is_update: false,
      must_include_id: null,
      type: 1,
      centerDialogVisible: false
    }
  },
  computed: {
    user_id() {
      return this.$store.state.user.id
    },
    execute_amount() {
      let tmp = 0
      if (this.cuForm.release_amount) {
        tmp = add(this.cuForm.release_amount, tmp)
      }
      if (this.cuForm.replace_amount) {
        tmp = add(this.cuForm.replace_amount, tmp)
      }
      return tmp
    },
    commission() {
      if (this.execute_amount && this.cuForm.accrued_amount) {
        let a = divide(this.cuForm.accrued_amount, '100')
        const sum = multiply(a, this.execute_amount)
        return sum + '元'
      } else {
        return undefined
      }
    }
  },
  watch: {
    media_type_count_amount_arr: {
      handler(media_type_count_amount_arr) {
        let amount = 0
        if (media_type_count_amount_arr && media_type_count_amount_arr.length > 0) {
          media_type_count_amount_arr.forEach(item => {
            if (item.amount && !isNaN(item.amount)) {
              amount = add(parseInt(item.amount), amount)
            }
          })
        }
        if (this.cuForm.billSaleProxyList && this.cuForm.billSaleProxyList.length > 0) {
          this.cuForm.billSaleProxyList.forEach(item => {
            if (item.proxyMediaDetailList && item.proxyMediaDetailList.length > 0) {
              item.proxyMediaDetailList.forEach(tmp => {
                if (tmp.fill_amount && !isNaN(tmp.fill_amount)) {
                  amount = add(parseInt(tmp.fill_amount), amount)
                }
              })
            }
          })
        }
        if (this.execute_amount && amount !== 0) {
          let tmp = divide(this.execute_amount, amount).toFixed(4)
          this.cuForm.discount = multiply(tmp, '100')
        }
      },
      deep: true
    },
    'cuForm.billSaleProxyList': {
      handler(billSaleProxyList) {
        let amount = 0
        if (this.media_type_count_amount_arr && this.media_type_count_amount_arr.length > 0) {
          this.media_type_count_amount_arr.forEach(item => {
            if (item.amount && !isNaN(item.amount)) {
              amount = add(parseInt(item.amount), amount)
            }
          })
        }
        if (billSaleProxyList && billSaleProxyList.length > 0) {
          billSaleProxyList.forEach(item => {
            if (item.proxyMediaDetailList && item.proxyMediaDetailList.length > 0) {
              item.proxyMediaDetailList.forEach(tmp => {
                if (tmp.fill_amount && !isNaN(tmp.fill_amount)) {
                  amount = add(parseInt(tmp.fill_amount), amount)
                }
              })
            }
          })
        }
        if (this.execute_amount && amount !== 0) {
          let tmp = divide(this.execute_amount, amount).toFixed(4)
          this.cuForm.discount = multiply(tmp, '100')
        }
      },
      deep: true
    },
    execute_amount(val) {
      this.cuForm.execute_amount = val
      let amount = 0
      if (this.media_type_count_amount_arr && this.media_type_count_amount_arr.length > 0) {
        this.media_type_count_amount_arr.forEach(item => {
          if (item.amount && !isNaN(item.amount)) {
            amount = add(parseInt(item.amount), amount)
          }
        })
      }
      if (this.cuForm.billSaleProxyList && this.cuForm.billSaleProxyList.length > 0) {
        this.cuForm.billSaleProxyList.forEach(item => {
          if (item.proxyMediaDetailList && item.proxyMediaDetailList.length > 0) {
            item.proxyMediaDetailList.forEach(tmp => {
              if (tmp.fill_amount && !isNaN(tmp.fill_amount)) {
                amount = add(parseInt(tmp.fill_amount), amount)
              }
            })
          }
        })
      }
      if (this.execute_amount && amount !== 0) {
        let tmp = divide(this.execute_amount, amount).toFixed(4)
        this.cuForm.discount = multiply(tmp, '100')
      }
    },
  },
  created() {
    this.initCompanyArr()
  },
  methods: {
    /**
     * 初始化子公司数组
     */
    initCompanyArr() {
      get_company().then(res => {
        this.companyArr = res.data
      })
    },
    /**
     * 客户选择框改变
     */
    customerChange(id) {
      this.clearContractId()
      listByCustomerId({ customerId: id }).then(res => {
        this.contractArr = res.data
      })
    },
    /**
     * 合同客户名称change事件
     * @param data
     */
    contractChange(data) {
      this.clearPlanId()
      this.cuForm.contract_num = data.contract_num
      this.proxyMediaDetailList = []
      this.cuForm.billSaleProxyList = []
      this.cuForm.contract_id = data.id
      this.cuForm.dept_id = data.part_b_id
      this.discounted_price = data.discounted_price
      this.initPlanList(data.id)
      contractDetail(data.id).then(res => {
        this.proxyMediaDetailList = res.data.proxyMediaDetailList
        this.cuForm.billSaleProxyList.push({
          proxy_company_name: null,
          proxy_amount: null,
          proxyMediaDetailList: cloneDeep(this.proxyMediaDetailList)
        })
      })
    },
    clearPlanId() {
      if (this.cuForm.intention_scheme !== null) {
        this.cuForm.intention_scheme = null
      }
      this.cuForm.choose_id = null
      this.cuForm.daterange_id = null
      if (this.cuForm.intention_scheme_id !== null) {
        this.cuForm.intention_scheme_id = null
      }
      this.planArr = []
      this.cuForm.actual_execute_time_start = null
      this.cuForm.actual_execute_time_end = null
    },
    clearContractId() {
      this.cuForm.contract_id = null
      this.cuForm.contract = null
      this.contractArr = []
      this.discounted_price = null
      this.billSaleProxyList = []
      this.cuForm.billSaleProxyList = []
      this.cuForm.contract_num = null
      this.clearPlanId()
    },
    /**
     * 获取方案列表
     */
    initPlanList(related_id) {
      listByRelated({
        related_id: related_id,
        related_type: 1,
        must_include_id: this.must_include_id,
        type: this.type
      }).then(res => {
        this.planArr = res.data
        this.cuForm.intention_scheme = this.planArr.find(item => item.id === this.cuForm.intention_scheme_id)
      })
    },
    async planChange(data, flag = false) {
      this.cuForm.choose_id = data.choose_id
      this.cuForm.intention_scheme_id = data.id
      this.cuForm.daterange_id = data.daterange_id
      this.cuForm.actual_execute_time_start = data.daterange_start_at
      this.cuForm.actual_execute_time_end = data.daterange_end_at
      let loading
      if (flag) {
        loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      }
      await planDetail({ id: data.id }).then(res => {
        this.cuForm.tmpDataList = formatData(res)
      }).catch(() => {
        loading.close()
      })
      if (flag) {
        media_type_count_amount({ customerId: this.cuForm.customer_id, dateRangeId: data.daterange_id }).then(res => {
          this.media_type_count_amount_arr = res.data.filter(item => item.spec_count != 0)
          this.cuForm.billSaleMediaAmountList = res.data.filter(item => item.spec_count != 0).map(item => {
            return {
              media_type_spec_id: item.media_type_spec_id,
              media_type_spec_price_id: item.media_type_spec_price_id,
              name: item.name,
              media_count: item.spec_count,
              fill_amount: null,
              has_price_day: item.has_price_day,
              has_price_week: item.has_price_week,
              has_price_month: item.has_price_month,
              price: null
            }
          })
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }
    },
    initCustomerArr(flag = false) {
      if (flag) {
        list_all().then(res => {
          this.customerArr = res.data
        })
      } else {
        company_list_all().then(res => {
          this.customerArr = res.data
        })
      }
    },
    /**
     * 获取时间间隔 开始日期也算一天
     * @param startDate
     * @param endDate
     * @returns {number}
     */
    getDaysBetween(startDate, endDate) {
      let number = getDaysBetween(startDate, endDate) + 1
      return isNaN(number) ? '选择方案后自动计算' : number
    },
    /**
     * 填写金额改变时修改对应类型的值
     * @param item
     * @param type
     * @param fill_amount
     */
    fillAmountChange(item, type, fill_amount) {
      if (fill_amount) {
        // 计算出每天的价格
        let time = this.getDaysBetween(this.cuForm.actual_execute_time_start, this.cuForm.actual_execute_time_end)
        let num = divide(fill_amount, multiply(item.media_count, time))
        if (num.toString().indexOf('.') > -1) {
          num = parseFloat(num.toString().substr(0, num.toString().indexOf('.') + 5))
        }
        if (type === 'day') {
          item.day_price = num.toFixed(2)
          return item.day_price
        } else if (type === 'week') {
          item.week_price = multiply(num, 7).toFixed(2)
          return item.week_price
        } else {
          item.month_price = multiply(num, 30).toFixed(2)
          return item.month_price
        }
      } else {
        return null
      }
    },
    async init() {
      this.formLoading = true
      await detail({ id: this.saleOrderId }).then(res => {
        this.cuForm = res.data
        this.type = res.data.type
        this.must_include_id = this.cuForm.intention_scheme_id
        if (this.cuForm.intention_scheme_related_type === 2) {
          this.is_update = true
        }
        media_type_count_amount({
          customerId: this.cuForm.customer_id,
          dateRangeId: this.cuForm.daterange_id
        }).then(res => {
          this.media_type_count_amount_arr = res.data.filter(item => item.spec_count != 0)
          this.$set(this.cuForm, 'billSaleMediaAmountList', cloneDeep(this.cuForm.mediaAmountVOList))
        })
        this.$set(this.cuForm, 'billSaleProxyList', cloneDeep(this.cuForm.billSaleProxies))
        this.cuForm.tmpDataList = formatData(res)
      })
      const flowStatus = this.cuForm.flow_status
      if (flowStatus == 3 || flowStatus == 4) {
        this.initCustomerArr()
      } else {
        this.initCustomerArr(true)
      }
      await listByCustomerId({ customerId: this.cuForm.customer_id }).then(res => {
        this.contractArr = res.data
      })
      this.cuForm.contract = this.contractArr.find(item => item.id === this.cuForm.contract_id)
      this.discounted_price = ((this.cuForm.contract || {}).discounted_price || 0)
      listByRelated({
        related_id: this.cuForm.intention_scheme_related_id,
        related_type: this.cuForm.intention_scheme_related_type,
        must_include_id: this.must_include_id
      }).then(res => {
        this.planArr = res.data
        this.cuForm.intention_scheme = this.planArr.find(item => item.id === this.cuForm.intention_scheme_id)
        this.planChange(this.cuForm.intention_scheme)
        this.formLoading = false
      })
    },
    open() {
      this.centerDialogVisible = true
    }
  }
}
</script>

<style scoped>
.app_main {
  padding-left: 20px;
  padding-right: 20px;
  max-height: 600px;
  overflow-y: auto;
}

.mailTable {
  width: 100%;
  font-size: 14px;
  margin: 0 auto 10px auto;
  border-collapse: collapse;
}

.mailTable tr td {
  height: 60px;
  line-height: 35px;
  box-sizing: border-box;
  padding: 0 10px;
  border-bottom: 1px solid #E6EAEE;
  border-right: 1px solid #E6EAEE;
  text-align: center;
}

.firstTr td {
  border-top: 1px solid #E6EAEE;
}

.firstTd {
  border-left: 1px solid #E6EAEE;
}

.mailTable tr td.column {
  text-align: center;
  /*border: 1px solid #8c939d;*/
}

.header {
  text-align: center;
  font-size: 25px;
  font-weight: bold;
  margin: 10px auto;
}

.tip {
  color: red;
}

/deep/ .el-form-item {
  margin-bottom: 0;
}

/deep/ .el-form-item__content {
  line-height: 0;
}

.tip_td {
  width: 10% !important;
  padding: 0 20px !important;
  background-color: #F5F7FA;
  font-weight: bold;
}

.proxyTable {
  width: 100%;
  font-size: 12px;
}

.proxyTable tr td {
  line-height: 23px;
  padding: 6px 0;
  height: auto;
}

/deep/ .el-input.is-disabled .el-input__inner {
  background-color: white;
  color: black;
}

/deep/ .el-textarea.is-disabled .el-textarea__inner {
  background-color: white;
  color: black;
}

/deep/ .el-radio__input.is-disabled + span.el-radio__label {
  color: black;
}

/deep/ .el-radio__input.is-checked .el-radio__inner {
  border-color: #409EFF;
  background: #409EFF
}

/deep/ .el-radio__input.is-disabled.is-checked .el-radio__inner::after {
  width: 4px;
  height: 4px;
  border-radius: 100%;
  background-color: #FFF;
}

.content_td {
  width: 40%;
}

@media screen and (max-width: 1920px) {
  /*当屏幕尺寸小于600px时，应用下面的CSS样式*/
  .mailTable {
    width: 95%;
    font-size: 14px;
    margin: 0 auto 10px auto;
    border-collapse: collapse;
  }
}

@media screen and (max-width: 1600px) {
  /*当屏幕尺寸小于600px时，应用下面的CSS样式*/
  .mailTable {
    width: 99%;
    font-size: 14px;
    margin: 0 auto 10px auto;
    border-collapse: collapse;
  }
}
</style>
